package com.sunday.common.netty.e7_Websocket.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.websocketx.*;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;

@Slf4j
public class WebSocketClient {

    private static final String SERVER_HOST = "127.0.0.1";
    private static final int SERVER_PORT = 8833;
    private static final String SERVER_PATH = "ws";

    private static final String URL = "ws://" + SERVER_HOST + ":" + SERVER_PORT + "/" + SERVER_PATH;

    public static void main(String[] args) throws Exception {

        URI uri = new URI(URL);

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            WebSocketClientHandler handler =
                    new WebSocketClientHandler(
                            // WebSocketClientHandshakerFactory.newHandshaker 方法的第三个参数是用于指定 WebSocket 协议的子协议，这里使用 null 表示不指定子协议。
                            WebSocketClientHandshakerFactory.newHandshaker(
                                    uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()));

            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new WebsocketClientChannel(handler));

            Channel ch = b.connect(SERVER_HOST, SERVER_PORT).sync().channel();
            handler.handshakeFuture().sync();

            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String msg = console.readLine();
                if (msg == null) {
                    break;
                } else if ("bye".equals(msg.toLowerCase())) {
                    ch.writeAndFlush(new CloseWebSocketFrame());
                    ch.closeFuture().sync();
                    break;
                } else if ("ping".equals(msg.toLowerCase())) {
                    WebSocketFrame frame = new PingWebSocketFrame(Unpooled.wrappedBuffer(new byte[]{8, 1, 8, 1}));
                    ch.writeAndFlush(frame);
                } else {
                    WebSocketFrame frame = new TextWebSocketFrame(msg);
                    ch.writeAndFlush(frame);
                }
            }
        } finally {
            group.shutdownGracefully();
        }
    }

}
